using System;
using System.Configuration;
using System.Web;
using System.Web.UI;
using facebook;
using System.Collections.Generic;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page 
{
    //Create a Facebook service object for connecting to the facebook.
    protected facebook.Components.FacebookService _fbService = new facebook.Components.FacebookService();
    
    /// <summary>
    /// Page_Load event for the page. Here we will be authenticating the user and
    /// setting the properties of our Facebook service object.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
         //Set the values for our Facebook service object's properties from our 
        //web config file constants(specific to our application).         
        _fbService.ApplicationKey = ConfigurationManager.AppSettings["AppKey"];
        _fbService.Secret = ConfigurationManager.AppSettings["Secret"];
        _fbService.IsDesktopApplication = Convert.ToBoolean(ConfigurationManager.AppSettings["Desktop"]);

        try
        {
            string sessionKey = Session["facebook_session_key"] as String;
            string userId = Session["facebook_userId"] as String;
            // When the user uses the Facebook login page, the redirect back here 
            // will will have the auth_token in the query params
            string authToken = Request.QueryString["auth_token"];
            
            //We have already established a session on behalf of this user
            if (!String.IsNullOrEmpty(sessionKey))
            {
                _fbService.SessionKey = sessionKey;
                _fbService.uid = Convert.ToInt64(userId);
                
            }
            // This will be executed when Facebook login redirects to our page
            else if (!String.IsNullOrEmpty(authToken))
            {
                _fbService.CreateSession(authToken);
                Session["facebook_session_key"] = _fbService.SessionKey;
                Session["facebook_userId"] = _fbService.uid.ToString();
                Session["facebook_session_expires"] = _fbService.SessionExpires;
            }

            //We can excess the user Details if we have a valid user Id.
            if (_fbService.uid.ToString() != "0")
            {
                facebook.Schema.user user = _fbService.users.getInfo();

                SetControlVisibility(_fbService.uid.ToString());                
                
                //function for printing user greetings.
                GetUserName(user);

                //function for Extracting User Profile.
                SetUserProfile(user);

                //function for retreiving user's friends list.
                GetUsersFriendsList();
              
            }
        }        
        catch (Exception ex)
        {            
            lblUserName.Text = ex.Message.ToString();          
        }
    }
  
    /// <summary>
    /// Using the ids of all the frinds we will build a comma seperated string,
    /// then we will access the user details for each id in our comma seperated string.
    /// </summary>
    private void GetUsersFriendsList()
    {
        String uids = String.Empty;
        IList<facebook.Schema.user> userFriendsInfo;

        friends friendUid = new friends(_fbService.API);
        IList<long> ids = friendUid.get();

        for (int i = 0; i < ids.Count; i++)
        {
            uids = uids + "," + ids[i];
        }

        if (uids != String.Empty)
        {
            userFriendsInfo = _fbService.users.getInfo(uids);

            foreach (facebook.Schema.user u in userFriendsInfo)
            {
                lstFriends.Items.Add(u.name);
            }
        }
    }


    /// <summary>
    /// Facebook provides a built in web control to show the User profile. 
    /// All we need to do here is to pass our user object to that control.
    /// </summary>
    /// <param name="user"></param>
    private void SetUserProfile(facebook.Schema.user user)
    {
        UserProfile1.User = user;
    }

    /// <summary>
    /// Function for setting the visibility of the controls.
    /// </summary>
    /// <param name="uid"></param>
    private void SetControlVisibility(string uid)
    {
        //For a valid user, hide the login button and show the other control.
        if (uid != "0")
        {
            btnLogin.Visible = false;
            table2.Visible = true;
            lblGreetUser.Visible=true;
            lblGreet.Visible = true;
            lblUserName.Visible = true;
            lblFriendsList.Visible = true;
            lstFriends.Visible = true;
            UserProfile1.Visible = true;
        }        
    }

    /// <summary>
    /// Facebook user object has variour properties for excessing the user details.
    /// Here we are using the first_name and the last_name property.
    /// </summary>
    /// <param name="user"></param>
    private void GetUserName(facebook.Schema.user user)
    {       
        lblUserName.Text = user.first_name + " " + user.last_name;
    }
     
    /// <summary>
    /// When user clicks on the login button we have to redirect
    /// them to the Facebook loging.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        Response.Redirect(@"http://www.facebook.com/login.php?api_key=" +
       _fbService.ApplicationKey + @"&v=1.0");
    }
}
